// const mySqlServer = require("../mysql/index.js")
require('dotenv').config()
// const { DB_HOST, DB_PORT, ENV, PRO_HOST } = process.env
const { getFile } = require('../models/getfile')
const { Op } = require("sequelize") // 操作符
const model = require('../models/model')
const CategoryOne = model.categoryOne.CategoryOne
const CategoryTwo = model.categoryTwo.CategoryTwo
const MyGoods = model.goodsdetails.MyGoods
const MyGoodsListSku = model.goodsdetailsSku.MyGoodsListSku //获取模型
const MyGoodsListType = model.goodsdetailsType.MyGoodsListType //获取模型
const MyGoodsList = model.goodsdetailsList.MyGoodsList //获取模型

// 获取商品一级分类
exports.categoryOne = async(ctx, next) => {
  const res = await CategoryOne.findAll()
  if (res) {
    ctx.success(res, '成功')
  } else {
    ctx.fail('失败', -1)
  }
}
// 获取商品二级分类
exports.categoryTwo = async(ctx, next) => {
  const { id } = ctx.request.body
  if (!id) {
    ctx.fail('参数错误', -1)
    return
  }
  function allFn() {
    return new Promise(async(resolve) => {
      const res = await CategoryTwo.findAll({ where: { parentId: id }})
      if (res.length > 0) {
        let flag = 0
        for (let i = 0; i < res.length; i++) {
          getFile(res[i].icon).then(file_url => {
            flag++
            res[i].icon = file_url
            if (flag === res.length) {
              resolve(res)
            }
          })
        }
      } else {
        resolve(res)
      }
    })
  }
  const res = await allFn()
  if (res != -1) {
    ctx.success(res, '成功')
  } else {
    ctx.fail('失败', -1)
  }
}
// 根据二级分类Id || 商品名称 获取商品列表
exports.getGoodsList = async(ctx, next) => {
  // orderType 排序类别('' 综合排序，salesDESC销量降序， sales销量升序，price价格升序，priceDESC价格降序)
  const { categoryTwoId, page, size, name, orderType } = ctx.request.body
  if (!page || !size) {
    ctx.fail('参数错误', -1)
    return
  }
  let order = []
  switch (orderType) {
    case 'salesDESC': // 销量降序
      order = [['sales', 'DESC']]
      break;
    case 'sales': // 销量升序
      order = [['sales', 'ASC']]
      break
    case 'price': // 价格升序
      order = [['price', 'ASC']]
      break
    case 'priceDESC': // 价格降序
      order = [['price', 'DESC']]
      break
    default: // 综合排序
      order = [['updateTime', 'DESC']]
      break;
  }
  // 获取商品的相关图片总集
  function getFileAll({ iconId, homeImageIds, detailsImageIds }) {
    return new Promise(async(resolve) => {
      const iconUrl = await getFile(iconId)
      const homeImageUrl = await getFile(homeImageIds)
      const detailsImageUrl = await getFile(detailsImageIds)
      resolve({
        iconUrl,
        homeImageUrl,
        detailsImageUrl
      })
    })
  }
  const res = await MyGoods.findAndCountAll({
    order,
    offset: (page-1) * size,
    limit: parseInt(size),
    where: {
      parentId: categoryTwoId ? categoryTwoId : undefined,
      name: {
        [Op.like]: `%${name ? name : ''}%`
      }
    }
  })
  console.log(res, 'res')
  if (res.rows.length > 0) {
    let flag = 0
    for (let i = 0; i < res.rows.length; i++) {
      getFileAll(res.rows[i]).then(({ iconUrl, homeImageUrl, detailsImageUrl }) => {
        res.rows[i].iconId = iconUrl
        res.rows[i].homeImageIds = homeImageUrl
        res.rows[i].detailsImageIds = detailsImageUrl
        res.rows[i].none_sku = res.rows[i].none_sku ? true : false
        flag++
        // 异步循环完成
        if (flag === res.rows.length) {
          ctx.success({
            total: res.count, // 总页数
            pageNum: Math.trunc((res.count + (size -1) )/size), // 分页数量
            page: parseInt(page), // 页码
            size: parseInt(size), // 页数
            list: res.rows
          })
        }
      })
    }
  } else {
    ctx.success({
      total: res.count, // 总页数
      pageNum: Math.trunc((res.count + (size -1) )/size), // 分页数量
      page: parseInt(page), // 页码
      size: parseInt(size), // 页数
      list: res.rows
    })
  }
}

// 根据商品id 获取详情
exports.goodDetails = async (ctx, next) => {
  const { getGoodsDetail } = require('../models/utils')
  const { id } = ctx.request.body
  if (!id) {
    ctx.fail('参数错误', -1)
    return
  }
  const res = await getGoodsDetail(id)
  if (res != -1) {
    ctx.success(res, '成功')
  } else {
    ctx.fail('失败', -1)
  }
}


exports.searchGoodsList = async(ctx) => {
  const { name } = ctx.request.body
  if (!name) {
    ctx.success([], '成功')
    return
  }
  function allFn() {
    return new Promise(async(resolve) => {
      // 分割
      let nameList = name.split(' ').map(item => {
        return { name: { [Op.like]: `%${item}%` }}
      })
      const res = await MyGoods.findAll({ where: {
        [Op.or]: nameList
      }})
      if (res.length > 0) {
        res.forEach(item => item.none_sku = item.none_sku === 1)
        resolve(res)
      } else {
        resolve(res)
      }
    })
  }
  const res = await allFn()
  ctx.success(res, '成功')
}